<template>
  <div class="relative page-container give-car-wrapper">
    <div class="page-form-block">
      <summary-info :summaryList="summaryLease" />
    </div>
    <a-divider />
    <page-form :model="form" layout="vertical" :rules="rules" ref="formRef">
      <card title="续租信息">
        <page-form-row>
          <page-form-item field="endTime" label="续租后还车时间">
            <template #label-extra>
              <div class="rent-days"> 续租时长：{{ rentDays || '- 天' }} </div>
            </template>
            <i-date-picker
              show-time
              class="w-full"
              v-model="form.endTime"
              format="YYYY-MM-DD HH:mm"
              valueFormat="YYYY-MM-DD HH:mm:00"
              :disabled-date="disabledDate"
              :disabled-time="disabledTime"
              :show-now-btn="false"
              :time-picker-props="{
                format: 'HH:mm',
                defaultValue: '00:00',
              }"
              @change="changeTimeFn"
              position="br"
            />
          </page-form-item>
          <page-form-item label="续租备注" size="2/3">
            <i-textarea v-model="form.remark" />
          </page-form-item>
        </page-form-row>
      </card>
      <!-- 费用信息 -->
      <div class="relative fee-pane-content">
        <page-form :model="feeForm" ref="feeFormRef" layout="vertical">
          <card toggle>
            <template #title>续租费用</template>
            <template v-for="(item, index) in feeForm.orderFee" :key="index">
              <fee-pane
                :isReletOrder="true"
                :orderFormType="'reletOrder'"
                :orderFeeIndex="index"
                :showPriceCalendar="showPriceCalendar"
                :disabledOnlineFee="orderInfo.orderSource == 1"
                :prevFeeForm="prevFeeForm"
                @feeChange="feeChangeFn"
                @viewPriceCalendar="viewPriceCalendarFn"
              />
            </template>
          </card>
        </page-form>
      </div>
    </page-form>
  </div>
  <!-- 二次确认 -->
  <a-modal title="提示" v-model:visible="confirmVisible">
    <div v-for="(it, i) in resultMsg" :key="i">{{ it }}</div>
    <div>请确认是否排车？</div>
    <template #footer>
      <a-button @click="confirmVisible = false">关闭</a-button>
      <a-button type="primary" @click="confirmSubmit">确认</a-button>
    </template>
  </a-modal>
  <!-- 底部 footer -->
  <page-form-footer :ok-loading="okLoading" @ok="submitFn" />
  <!-- 价格日历 -->
  <price-calendar-modal ref="priceCalendarModalRef" />
</template>
<script setup name="ShortOrderReletOrder">
  import { ref, provide, computed } from 'vue'
  import { useRoute } from 'vue-router'
  import { computeRentDay, getShortOrdrDetails, reletOrder, getShortOrdrFeeDetail, calcPrice } from '@/api/order/sOrder'
  import feePane from './components/order-fee/fee-pane.vue'
  import iTextarea from '@/views/order/short-order/components/i-textarea.vue'
  import {
    buildCostInfoParam,
    initFeeDetail,
    getStoreTemplateDetail,
    handleStoreTemplateDetail,
    handleAddserviceDefaultFee,
  } from './components/order-fee/fee-utils.js'
  import { platoonCarCheck } from '@/api/asset/carStock'
  import useNavigate from '@/hooks/useNavigate'
  import summaryInfo from './components/summary-info.vue'
  import { Notification, Modal } from '@arco-design/web-vue'
  import priceCalendarModal from '@/views/business/price/car-model/form/components/price-calendar-modal.vue'
  import { getPriceCalendar } from '@/api/business/price.js'
  const { navigateBack } = useNavigate()
  import dayjs from 'dayjs'
  import useUserStore from '@/store/modules/user'
  const userStore = useUserStore()
  const route = useRoute()
  const orderId = route.params.id
  const orderInfo = ref({})

  const form = ref({
    id: orderId,
  })

  // 原费用信息
  const prevFeeForm = ref({})

  // 处理默认值
  // 租赁周期限制最小时长 60 分钟
  const timeRangeValidator = (value, callback) => {
    if (value) {
      let start = orderInfo.value.endTime
      let end = value
      if (start && end) {
        let diff = dayjs(end).diff(dayjs(start))
        if (diff < 60 * 60 * 1000) {
          callback('续租时长最短为1小时')
        }
      }
    }
    callback()
  }
  // 查看价格日历
  const priceCalendarModalRef = ref()
  // 是否显示价格日历按钮
  const showPriceCalendar = computed(() => {
    return !!priceModelId.value
  })
  const viewPriceCalendarFn = () => {
    priceCalendarModalRef.value.open(orderInfo.value.originalModelName)
    // 获取价格日历信息
    const param = {
      priceModelId: priceModelId.value,
      calendarDateS: dayjs(orderInfo.value.startTime).startOf('month').format('YYYY-MM-DD HH:mm:ss'),
    }
    getPriceCalendar(param).then((res) => {
      const result = res.result
      priceCalendarModalRef.value.setPriceList(result)
    })
  }
  const rules = {
    endTime: [{ required: true, message: '请选择续租后还车时间' }, { validator: timeRangeValidator }],
  }
  const formRef = ref()
  provide('form', form)

  const summaryLease = computed(() => {
    const orderInfoVal = orderInfo.value
    return [
      [
        {
          label: '预计租赁周期',
          value: orderInfoVal.startTime ? `${orderInfoVal.startTime} - ${orderInfoVal.endTime}` : '-',
        },
        { label: '租期', value: orderInfoVal.rentDays },
        { label: '订单来源', value: orderInfoVal.orderSourceName },
      ],
      [
        { label: '车型', value: orderInfoVal.originalModelName },
        { label: '交车车型', value: orderInfoVal.carModelName },
      ],
      [{ label: '交车车牌号', value: orderInfoVal.carLicenseNo }],
    ]
  })

  // 费用变化
  const feeChangeFn = (item, val, index) => {
    let feeDetailList = feeForm.value.orderFee[0].feeDetailList
    let option = feeDetailList[index].childrenList
    let itemName = item.itemName
    if (itemName == '日租价') {
      let target = option.find((item) => item.itemName == '车辆租金')
      if (target) target.amount = val * calcRate.value
    }
  }

  const priceTemplateId = ref()
  const feeFormRef = ref()
  const feeForm = ref({
    randomKey: 0,
    orderFee: [
      {
        // 费用类型（线上费用|线下费用）
        feeType: 1,
        feeDetailList: [],
        priceTemplateId: priceTemplateId,
        feeDetailTypeList: ['basicFee', 'addServiceFee', 'preferentialFee', 'otherFee'],
      },
    ],
  })
  provide('feeForm', feeForm)
  const cacheStoreTemplate = ref({})
  if (orderId) {
    getShortOrdrDetails({ id: orderId }).then((res) => {
      const result = res.result
      orderInfo.value = result.orderInfo
      // 处理默认值
      // 车务专员 | 当前登录者 id
      form.value.returnStaffId = orderInfo.value.returnStaffId || userStore.userId
      // 初始化 endTime
      let endTime = orderInfo.value.endTime
      if (endTime) {
        form.value.endTime = dayjs(endTime).add(1, 'day').format('YYYY-MM-DD HH:mm:ss')
        changeTimeFn(form.value.endTime)
      }

      // 读取门店模板配置
      getStoreTemplateDetail(orderInfo.value.siteId, 1, (storeTemplate, templateId) => {
        cacheStoreTemplate.value = storeTemplate
        let feeValue = feeForm.value
        initFeeDetail(feeValue, storeTemplate)
        // 更新费用模板 id
        priceTemplateId.value = templateId
        // 初始化费用
        setDefaultFee()
      })
    })

    // 获取原费用信息
    getShortOrdrFeeDetail({ id: orderId }).then((res) => {
      const result = res.result
      const orderFeeList = result.orderFeeList
      if (orderFeeList?.length > 0) {
        let rentFee = orderFeeList.find((item) => item.feeNameId == 1)
        prevFeeForm.value = {
          randomKey: 0,
          orderFee: [
            {
              // 费用类型（线上费用|线下费用）
              feeDetailList: [],
              feeDetailTypeList: ['basicFee', 'addServiceFee', 'preferentialFee', 'otherFee'],
            },
          ],
        }
        // 创建费用时的费用模板快照
        let priceTemplateSnapshot = rentFee.priceTemplateSnapshot
        // 解析后的费用模板
        let storeTemplate = null
        if (priceTemplateSnapshot) {
          priceTemplateSnapshot = JSON.parse(priceTemplateSnapshot)
          storeTemplate = handleStoreTemplateDetail(priceTemplateSnapshot)
        }
        initFeeDetail(prevFeeForm.value, storeTemplate)
        // 回显
        // 默认费用
        let feeDetailList = rentFee.feeDetailList
        let formfeeDetailList = prevFeeForm.value.orderFee[0].feeDetailList
        formfeeDetailList.forEach((formFeeDetailItem) => {
          let findResult = feeDetailList.find((item) => {
            let sameFeeCategory = item.feeCategory == formFeeDetailItem.feeCategory
            let sameFeeName = item.itemName == formFeeDetailItem.feeName
            return sameFeeCategory || sameFeeName
          })
          if (findResult) {
            formFeeDetailItem.categoryType = findResult.type
          } else {
            formFeeDetailItem.categoryType = 0
          }
          formFeeDetailItem.childrenList?.forEach((item) => {
            let findFeeDetail = findResult?.childrenList.find((feeDetailItem) => feeDetailItem.itemName == item.itemName)
            if (!findFeeDetail) {
              findFeeDetail = feeDetailList.find((feeDetailItem) => feeDetailItem.itemName == item.itemName)
            }
            if (findFeeDetail) {
              item.amount = findFeeDetail.amount
              item.id = findFeeDetail.id
              item.statics = true
            }
          })
        })
      }
    })
  }

  // 获取默认费用
  // 车型价格模板 id
  const priceModelId = ref()
  const calcRate = ref()
  const setDefaultFee = () => {
    const param = {
      id: form.value.id,
      siteId: orderInfo.value.siteId,
      modelId: orderInfo.value.originalModelId,
      endTime: form.value.endTime,
      type: 3,
    }
    calcPrice(param).then((res) => {
      const { basePrice, otherPrice, rate } = res.result
      if (basePrice) {
        priceModelId.value = basePrice.id
      } else {
        priceModelId.value = ''
      }
      calcRate.value = rate
      let feeValue = feeForm.value
      let feeDetailList = feeValue.orderFee[0].feeDetailList
      // 处理增值服务费默认值
      handleAddserviceDefaultFee(feeDetailList, cacheStoreTemplate.value, rate)
      // 初始化其他费用
      feeDetailList.forEach((feeCategory) => {
        const { childrenList } = feeCategory
        // 默认系统计算的费用包含，基础费用，押金费用以及增值服务费中的例如上门取车费、夜间服务费等费用
        if (childrenList && childrenList.length > 0) {
          childrenList.forEach((feeItem) => {
            // 费用名称
            let feeName = feeItem.itemName
            // basicPrice 费用
            if (feeName == '日租价') {
              if (basePrice?.avgPrice >= 0) feeItem.amount = basePrice?.avgPrice
            }
            if (feeName == '手续费') {
              if (basePrice?.poundageAmount >= 0) feeItem.amount = basePrice?.poundageAmount
            }
            // otherPrice 费用
            if (otherPrice && otherPrice.length > 0) {
              let findIndex = otherPrice.findIndex((item) => item.itemName == feeName)
              if (findIndex >= 0) {
                let fee = otherPrice[findIndex]
                feeItem.statics = true
                if (fee?.amount >= 0) {
                  feeItem.amount = fee.amount
                }
              }
            }
          })
          childrenList.forEach((it) => {
            if (['手续费', '车辆租金', '基础保险'].includes(it.itemName)) {
              it.amount = it.amount > 0 ? it.amount : ''
            }
          })
        }
      })
      // 当没有下单车型时，此时费用计算不会计算出下述几种费用，此时需要手动补充费用，补充0
      if (!basePrice) {
        feeDetailList.forEach((feeCategory) => {
          const { childrenList } = feeCategory
          if (childrenList && childrenList.length > 0) {
            childrenList.forEach((feeItem) => {
              // 费用名称
              let feeName = feeItem.itemName
              // basicPrice 费用
              if (['手续费', '车辆租金', '基础保险'].includes(feeName)) {
                feeItem.amount = ''
              }
              if (['日租价'].includes(feeName)) {
                feeItem.amount = 0
              }
            })
          }
        })
      }
    })
  }

  // disabled Date|Time
  const disabledDate = (dateVal) => {
    const prevDate = orderInfo.value.endTime
    if (!dateVal || !prevDate) {
      return false
    }
    // 存在限制最大范围
    // 当前时间是 23:50
    if (dayjs(prevDate).hour() == 23 && dayjs(prevDate).minute() == 59) {
      return dayjs(prevDate).add(1, 'd').startOf('day').valueOf() > dayjs(dateVal).valueOf()
    } else {
      return dayjs(prevDate).startOf('day').valueOf() > dayjs(dateVal).valueOf()
    }
  }
  const range = (start, end) => {
    const result = []
    for (let i = start; i < end; i++) {
      result.push(i)
    }
    return result
  }
  const disabledTime = (current) => {
    let options = {}
    let prevDate = orderInfo.value.endTime
    if (prevDate) {
      let currentTime = current ? dayjs(current) : dayjs()
      let currentTime_year = currentTime.year()
      let currentTime_month = currentTime.month()
      let currentTime_date = currentTime.date()
      let currentTime_hour = currentTime.hour()
      let prevDateTime = dayjs(prevDate)
      let prevDateTime_year = prevDateTime.year()
      let prevDateTime_month = prevDateTime.month()
      let prevDateTime_date = prevDateTime.date()
      let prevDateTime_hour = prevDateTime.hour()
      let prevDateTime_minute = prevDateTime.minute()
      if (prevDateTime_minute == 59) {
        options.disabledHours = () => range(0, prevDateTime_hour + 1)
        options.disabledMinutes = () => []
      } else {
        options.disabledHours = () => range(0, prevDateTime_hour)
        options.disabledMinutes = () => range(0, prevDateTime_minute + 1)
      }
      // 用户选择的是 未来 的天
      if (currentTime_year > prevDateTime_year || currentTime_month > prevDateTime_month || currentTime_date > prevDateTime_date) {
        options = {}
      } else {
        // 用户选择的是 未来 的小时
        if (currentTime_hour > prevDateTime_hour) {
          options.disabledMinutes = () => {
            return []
          }
        }
      }
    }
    return options
  }
  const rentDays = ref()
  const changeTimeFn = (value) => {
    let startTime = orderInfo.value.endTime
    if (value) {
      // 计算租期
      const param = {
        startTime: startTime,
        endTime: value,
        siteId: orderInfo.value.siteId,
      }
      computeRentDay(param).then((res) => {
        let { days } = res.result
        if (days.indexOf('小时') >= 0 && days.indexOf('天') >= 0) {
          days = days.replace('天', ' 天 ').replace('小时', ' 小时')
        } else {
          days = days.replace('天', ' 天').replace('小时', ' 小时')
        }
        rentDays.value = days
      })
      setDefaultFee()
    } else {
      rentDays.value = undefined
    }
  }
  // 排车校验
  const resultMsg = ref([])
  const confirmVisible = ref(false)
  const platoonCarVerify = (callback) => {
    const params = {
      refId: orderInfo.value.id,
      startTime: orderInfo.value.endTime,
      endTime: form.value.endTime,
      useType: 2,
      carId: orderInfo.value.carId,
    }
    platoonCarCheck(params).then((res) => {
      let msgList = res.result.resultMsg || []
      if (msgList.length) {
        resultMsg.value = msgList
        confirmVisible.value = true
        return
      }
      callback && callback()
    })
  }
  // 续租
  const reletFn = () => {
    let feeFormValue = feeForm.value
    let costInfo = buildCostInfoParam(feeFormValue)
    const param = {
      ...form.value,
      orderFee: {
        ...costInfo.orderFee[0],
        priceModelId: priceModelId.value,
      },
    }
    let beforeStatus = param.orderFee.feeDetailList.some((it) => {
      if (it.childrenList) {
        return it.childrenList.some((item) => {
          return item.amount === 0
        })
      } else {
        return it.amount === 0
      }
    })
    if (beforeStatus) {
      Modal.confirm({
        title: '提示',
        simple: true,
        cancelText: '关闭',
        okText: '确认',
        content: '请注意，金额为0时不生成费项信息',
        onOk: () => {
          toSubmitFn(param)
        },
      })
    } else {
      toSubmitFn(param)
    }
  }
  const toSubmitFn = (param) => {
    okLoading.value = true
    reletOrder(param)
      .then(() => {
        confirmVisible.value = false
        Notification.success({
          content: '续租成功',
          closable: true,
          duration: 3000,
        })
        navigateBack()
      })
      .finally(() => (okLoading.value = false))
  }
  // 二次询问确认
  const confirmSubmit = () => {
    if (orderInfo.value.orderSource == 2 && orderInfo.value.channelOrderMaintenance == 1) {
      orderConfirmFn()
    } else {
      reletFn()
    }
  }
  const okLoading = ref(false)
  const submitFn = () => {
    formRef.value.validate((error) => {
      if (!error) {
        feeFormRef.value.validate((error) => {
          if (!error) {
            platoonCarVerify(() => {
              confirmSubmit()
            })
          }
        })
      }
    })
  }
  // 自动维护的渠道订单
  const orderConfirmFn = () => {
    confirmVisible.value = false
    Modal.confirm({
      title: '提示',
      simple: true,
      cancelText: '取消',
      okText: '确认',
      bodyStyle: {
        'text-align': 'center',
      },
      content: '操作续租后，该笔订单不再自动同步渠道信息，需手动完成还车等操作，确认续租吗？',
      onOk: () => {
        reletFn()
      },
    })
  }
</script>
<style lang="less" scoped>
  :deep(.arco-card) {
    background-color: inherit;
  }
  .order-summary-pane {
    :deep {
      .field-label {
        width: 200px;
        display: inline-block;
        text-align: right;
      }
    }
  }
  .rent-days {
    color: rgb(var(--primary-6));
  }
</style>
